package com.cti.commons.delayqueue.config;

import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.cti.commons.delayqueue.handler.VisiableThreadPoolTaskExecutor;

import lombok.extern.slf4j.Slf4j;

/**
 * @author et.wang
 * @title: ThreadExecutorConfig
 * @description: 线程池配置
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(ThreadPoolProperties.class)
@EnableAsync
public class ThreadExecutorConfig {

    @Autowired
    private ThreadPoolProperties threadPoolProperties;

    @Bean
    public ThreadPoolTaskExecutor bucketPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor();
        //设置核心线程数
        executor.setCorePoolSize(threadPoolProperties.getBucketPool().getCorePoolSize());
        //设置最大线程数
        executor.setMaxPoolSize(threadPoolProperties.getBucketPool().getMaxPoolSize());
        //设置队列数
        executor.setQueueCapacity(threadPoolProperties.getBucketPool().getQueueCapacity());
        //设置线程名称前缀
        executor.setThreadNamePrefix("延时任务到期处理线程->");
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        // 设置拒绝策略.当工作队列已满,线程数为最大线程数的时候,接收新任务抛出RejectedExecutionException异常
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 执行初始化
        executor.initialize();
        return executor;
    }

    @Bean
    public ThreadPoolTaskExecutor customerPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor();
        //设置核心线程数
        executor.setCorePoolSize(threadPoolProperties.getCustomerPool().getCorePoolSize());
        //设置最大线程数
        executor.setMaxPoolSize(threadPoolProperties.getCustomerPool().getMaxPoolSize());
        //设置队列数
        executor.setQueueCapacity(threadPoolProperties.getCustomerPool().getQueueCapacity());
        //设置线程名称前缀
        executor.setThreadNamePrefix("延时队列消费线程->");
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        // 设置拒绝策略.当工作队列已满,线程数为最大线程数的时候,接收新任务抛出RejectedExecutionException异常
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 执行初始化
        executor.initialize();
        return executor;
    }

}